import type { RouteLocationNormalized } from 'vue-router';
import { defineStore } from 'pinia';
import {
  DEFAULT_ROUTE,
  DEFAULT_ROUTE_NAME,
  REDIRECT_ROUTE_NAME,
} from '@/router/constants';
import { isString } from '@/utils/is';
import { TabBarState, TagProps } from './types';

// 格式化tab栏数据
const formatTag = (route: RouteLocationNormalized): TagProps => {
  const { name, meta, fullPath, query } = route;
  return {
    title: meta.locale || '',
    name: String(name),
    fullPath,
    query,
    ignoreCache: meta.ignoreCache,
  };
};

// 禁止列表
const BAN_LIST = [REDIRECT_ROUTE_NAME];

const useAppStore = defineStore('tabBar', {
  state: (): TabBarState => ({
    // tab缓存列表名
    cacheTabList: new Set([DEFAULT_ROUTE_NAME]),
    // tab临时列表
    tagList: [DEFAULT_ROUTE],
  }),
  getters: {
    // 获取tab栏列表
    getTabList(): TagProps[] {
      return this.tagList;
    },
    // 获取tab栏列表名
    getCacheList(): string[] {
      return Array.from(this.cacheTabList);
    },
  },
  actions: {
    // 更新tab列表
    updateTabList(route: RouteLocationNormalized) {
      // 如果当前路由是重定向路由, 则不更新
      if (BAN_LIST.includes(route.name as string)) return;
      // 路由加入临时tab栏列表, 当前路由需要缓存则加入缓存tab栏列表名
      this.tagList.push(formatTag(route));
      if (!route.meta.ignoreCache) {
        this.cacheTabList.add(route.name as string);
      }
    },
    // 删除tab列表
    deleteTag(idx: number, tag: TagProps) {
      this.tagList.splice(idx, 1);
      this.cacheTabList.delete(tag.name);
    },
    // 添加tab缓存列表
    addCache(name: string) {
      if (isString(name) && name !== '') this.cacheTabList.add(name);
    },
    // 删除tab缓存列表
    deleteCache(tag: TagProps) {
      this.cacheTabList.delete(tag.name);
    },
    // 刷新tab列表
    freshTabList(tags: TagProps[]) {
      this.tagList = tags;
      this.cacheTabList.clear();
      // 要先判断ignoreCache
      this.tagList
        .filter((el) => !el.ignoreCache)
        .map((el) => el.name)
        .forEach((x) => this.cacheTabList.add(x));
    },
    // 重置tab列表
    resetTabList() {
      this.tagList = [DEFAULT_ROUTE];
      this.cacheTabList.clear();
      this.cacheTabList.add(DEFAULT_ROUTE_NAME);
    },
  },
});

export default useAppStore;
